<script setup>
import { onMounted, ref, reactive, computed } from 'vue';
import userControl from '../../apis/userControl';
import volunteerColumns from '../../utils/volunteerColmuns';
import refuse from '../../utils/refuseVolunteer';
import volunteerSelect from '../../utils/volunteerSelect';
import PaginationComponent from '../../components/pageHelper.vue';

// 当前激活的标签
const activeTab = ref('volunteerCheck');

// 定义各标签独立状态
const tabsState = reactive({
  volunteerCheck: {
    tableData: [],
    totalItems: 0,
    itemsPerPage: 10,
    currentPage: 1,
  },
  volunteerSelect: {
    tableData: [],
    totalItems: 0,
    itemsPerPage: 10,
    currentPage: 1,
  },
});

// 当前选中标签的状态
const currentTabState = computed(() => tabsState[activeTab.value]);

// 表单数据
const form = ref({
  volunteersId: '',
  volunteerName: '',
  objection: '',
});

// 提示类型
let notificationType = 'warning';
const Oneobjection = ref('');
const Twoobjection = ref('');

// 弹窗显示隐藏
const dialogFormVisible = ref(false);

// 监听标签的切换
const handleTabChange = (tabName) => {
  activeTab.value = tabName;
  if (tabsState[tabName].tableData.length === 0) {
    fetchData(tabName);
  }
};

// 获取数据
const fetchData = async (tabName) => {
  try {
    const state = tabsState[tabName]; // 获取当前标签状态
    let response = null;
    if (tabName === 'volunteerCheck') {
      response = await userControl.getVolunteerCheck({
        currentPage: state.currentPage,
        pageSize: state.itemsPerPage,
      });
    } else if (tabName === 'volunteerSelect') {
      response = await userControl.getVolunteerSelect({
        currentPage: state.currentPage,
        pageSize: state.itemsPerPage,
      });
    }

    if (response && response.data) {
      state.tableData = response.data;
      state.totalItems = response.total;
    } else {
      notificationType = 'info';
      throw new Error('无多余的数据，请重新刷新');
    }
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message || '加载数据失败',
      type: notificationType,
    });
  }
};

// 页面加载时默认加载第一个标签数据
onMounted(() => {
  fetchData('volunteerCheck');
});

// 监听分页变化
const handleCurrentPageChange = (page) => {
  currentTabState.value.currentPage = page;
  fetchData(activeTab.value); // 根据当前页数重新获取数据
};

// 监听每页条目数变化
const handlePageSizeChange = (size) => {
  currentTabState.value.itemsPerPage = size;
  fetchData(activeTab.value); // 根据每页条目数重新获取数据
};

// 审核通过操作
const handleClick = async (volunteersId) => {
  try {
    await ElMessageBox.confirm('请仔细确认你的操作', 'Warning', {
      confirmButtonText: '确认',
      cancelButtonText: '撤回',
      type: 'warning',
    });
    await userControl.pass({ volunteersId });
    ElMessage({ type: 'success', message: '审核通过' });
    fetchData(activeTab.value); // 刷新数据
  } catch (error) {
    if (error === 'cancel') {
      ElMessage({ type: 'info', message: '已撤回' });
    } else {
      ElNotification({
        title: '错误',
        message: error.message || '操作失败',
        type: 'error',
      });
    }
  }
};

// 拒绝操作 - 打开弹窗并赋值
const handleClickRefuse = (data) => {
  dialogFormVisible.value = true;
  form.value.volunteersId = data.volunteersId;
  form.value.volunteerName = data.volunteerName;
};

// 拒绝确认操作
const handleConfirmRefuse = async () => {
  try {
    form.value.objection = Oneobjection.value + Twoobjection.value;
    await userControl.refuse({ ...form.value });
    ElMessage({ type: 'success', message: '填写完成' });
    dialogFormVisible.value = false;
    fetchData(activeTab.value); // 刷新数据
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message || '操作失败',
      type: 'error',
    });
  }
};
</script>

<template>
  <div>
    <el-tabs
      v-model="activeTab"
      @tab-change="handleTabChange"
      type="border-card"
    >
      <el-tab-pane name="volunteerCheck" label="志愿审核">
        <el-card>
          <el-table
            :data="currentTabState.tableData"
            style="width: 100%"
            border
          >
            <el-table-column
              v-for="(column, index) in volunteerColumns"
              :key="index"
              :label="column.label"
              :prop="column.props"
              :min-width="column.minWidth || 120"
              :fixed="column.fixed || null"
            />
            <el-table-column fixed="right" label="审核" min-width="120">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleClick(scope.row.volunteersId)"
                  >同意</el-button
                >
                <el-button
                  type="danger"
                  size="small"
                  @click="handleClickRefuse(scope.row)"
                  >退返</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <PaginationComponent
            :totalItems="currentTabState.totalItems"
            :itemsPerPage="currentTabState.itemsPerPage"
            :currentPage="currentTabState.currentPage"
            @currentChange="handleCurrentPageChange"
            @sizeChange="handlePageSizeChange"
          />
        </el-card>

        <el-dialog v-model="dialogFormVisible" title="退返理由书" width="500px">
          <el-form :model="form">
            <el-form-item label="请求人身份号码">
              <el-input v-model="form.volunteersId" readonly />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="form.volunteerName" readonly />
            </el-form-item>
            <el-form-item label="退返理由类别">
              <el-select v-model="Oneobjection" placeholder="请选择理由">
                <el-option
                  v-for="(value, index) in refuse"
                  :key="index"
                  :label="value.label"
                  :value="value.props"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="详细理由">
              <el-input
                type="textarea"
                v-model="Twoobjection"
                placeholder="请输入详细理由"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogFormVisible = false">撤回</el-button>
            <el-button type="primary" @click="handleConfirmRefuse"
              >确认</el-button
            >
          </template>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane name="volunteerSelect" label="志愿者查询">
        <el-card>
          <el-table
            :data="currentTabState.tableData"
            style="width: 100%"
            border
          >
            <el-table-column
              v-for="(column, index) in volunteerSelect"
              :key="index"
              :label="column.label"
              :prop="column.props"
              :min-width="column.minWidth || 120"
              :fixed="column.fixed || null"
            />
          </el-table>
          <PaginationComponent
            :totalItems="currentTabState.totalItems"
            :itemsPerPage="currentTabState.itemsPerPage"
            :currentPage="currentTabState.currentPage"
            @currentChange="handleCurrentPageChange"
            @sizeChange="handlePageSizeChange"
          />
        </el-card> </el-tab-pane
    ></el-tabs>
  </div>
</template>
